import BaseService from './base';
import Sequelize from 'sequelize';
const Op = Sequelize.Op;

export default class EmailsService extends BaseService {
  constructor({ emailsDao }) {
    super();
    this.emailsDao = emailsDao
  }

  async getEmailsAll (emails) {
    const [err, list] = await this.emailsDao.getEmailsAll({
      where: {
        mark: {[Op.ne]: emails.mark}
      }
    });
    if (err) {
      return this.fail('获取列表失败', null, err);
    }
    return this.success('查询成功', list);
  }

  async getEmailslist(emails) {
    const [err, count, rows] = await this.emailsDao.getEmailslist({
      where: {
        t_email: emails.t_email === '' ? {
          [Op.ne]: null
        } : emails.t_email,
        mark: {[Op.ne]: emails.mark}
      },
      limit: emails.limit,
      offset: emails.limit * (emails.offset - 1),
      distinct: true
    });
    if (err) {
      return this.fail('获取列表失败', null, err);
    }
    return this.success('查询成功', count, rows);
  }

  async addEmails(emails) {
    const [exsitErr, itemExsit] = await this.emailsDao.findOne({
      where: {
        t_email: emails.t_email
      }
    });
    if (exsitErr) {
      return this.fail('添加失败', null, exsitErr);
    }
    if (itemExsit) {
      return this.fail('已存在');
    }
    const [addErr] = await this.emailsDao.addEmails(emails);
    if (addErr) {
      return this.fail('添加失败', null, addErr);
    }
    return this.success('添加成功')
  }

  async delEmails(emails) {
    const [err, updateEmails] = await this.emailsDao.update(emails, {
      where: {
        id: emails.id
      }
    });
    if (err) {
      return this.fail('删除失败');
    }
    return this.success('删除成功');
  }

  async updateEmails(emails) {
    const [err, updateEmails] = await this.emailsDao.update(emails, {
      where: {
        id: emails.id
      }
    });
    if (err) {
      return this.fail('更新失败');
    }
    return this.success('更新成功');
  }
}